package com.recommendation.action;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.recommendation.db.DBUtils;
import com.recommendation.db.Dao;
import com.recommendation.domain.RecommendItem;

@Results({
	  @Result(location="log.jsp")
})
public class LogAction extends ActionBase{

	private List<RecommendItem> items;
	
	public String execute()
	{
		long userId = getUserId();
		Connection conn = null;
		try {
			conn = DBUtils.getConnection();
			items = Dao.INSTANCE.getRecentRecommendedItems(userId, conn);
			int length = items.size();
			if (length > 20)
			{
				List<Long> numIids = new ArrayList<Long>();
				for (int i = 1; i <= 5; i++)
				{
					RecommendItem item = items.get(length - i);
					numIids.add(item.getNumIid());
				}
				Dao.INSTANCE.deleteRecentRecommendedItems(numIids, conn);
			}
		} catch (NamingException e) {
			error(e);
		} catch (SQLException e) {
			error(e);
		}
		finally
		{
			DBUtils.close(conn, null, null);
		}
		return SUCCESS;
	}

	public void setItems(List<RecommendItem> items) {
		this.items = items;
	}

	public List<RecommendItem> getItems() {
		return items;
	}
}
